//
//  SEGTarget_ActivityManage.m
//  ExcellentHome
//
//  Created by 揭婧雯 on 2017/8/2.
//  Copyright © 2017年 陈区. All rights reserved.
//

#import "SEGTarget_ActivityManage.h"
#import "SEGActivityRootViewController.h"
#import "SEGActivityCollectViewController.h"
#import "SEGActivityOffLineViewController.h"
#import "SEGActivityLotteryViewController.h"
#import "SEGActivityTriggerViewController.h"
#import "SEGActivitySignViewController.h"
#import "SEGActivityInvitationViewController.h"
#import "SEGWinRecordListViewController.h"
#import "SEGWinRecordDetailViewController.h"
#import "SEGActivityTriggerLotteryViewController.h"
#import "SEGActivityCommentDetailViewController.h"
#import "SEGStaffDetailPresentationController.h"
#import "SEGActivityListViewController.h"

#import "SEGActivityLotteryBubbleButton.h"
#import "SEGActivitySignBubbleButton.h"
#import "SEGFinishActivityTaskDetailViewController.h"
#import "SEGCommonConfig.h"
#import "SEGAnalyseBehaviorDefine.h"

#import <SEGViewModel/SEGActivityDetailViewModel.h>
#import <SEGViewModel/SEGSignActivityDetailViewModel.h>


typedef void(^SEGActicityCheckSignButtonShowBlock) (NSString *actID, BOOL isShow);

@interface SEGTarget_ActivityManage ()

@property (nonatomic, strong) SEGActivityDetailViewModel *viewModel;
@property (nonatomic, strong) SEGSignActivityDetailViewModel *taskViewModel;

@end

@implementation SEGTarget_ActivityManage
/**
 * 初始化活动列表
 * @author Wendy
 * @param params 跳转参数
 */
- (UIViewController*)segAction_initActivityRootViewController:(NSDictionary *)params
{
    SEGActivityRootViewController *activity = [[SEGActivityRootViewController alloc] init];
    activity.hidesBottomBarWhenPushed = YES;
    activity.aTitle = params[@"title"];
    return activity;
}

/// 初始化我参与的活动列表
/// @param params 跳转参数
- (UIViewController *)segAction_initMyParticipatedActivityController:(NSDictionary *)params {
    SEGActivityListViewController *myParticipatedVC = [[SEGActivityListViewController alloc] initWithIsRecommand:NO isMine:YES];
    if ([params.allKeys containsObject:@"displayTitle"]) {
        myParticipatedVC.displayTitle = ValueToString(params[@"displayTitle"]);
    }
    return myParticipatedVC;
}

/**
 * 根据活动ID跳转到对应的活动详情页
 * @author Wendy
 * @param params 跳转参数，必传参数actId、nav
 */
- (void)segAction_goToActivityDetailViewController:(NSDictionary *)params
{
    NSString *actId = [params objectForKey:@"actId"];
    UINavigationController *nav = nil;
    if ([params[@"nav"] isKindOfClass:[UINavigationController class]]) {
        nav = params[@"nav"];
    }
    if ((!actId) || (!nav)) {
        return;
    }
    
    [SVProgressHUD show];
    self.viewModel.actId = actId;
    // 设置已经加载过，为了不调用积分和请求签到的接口
    self.viewModel.isAreadyLoad = YES;
    [self.viewModel.requestActicityDeatilSignal subscribeNext:^(id  _Nullable x) {
        [SVProgressHUD dismiss];
        SEGActivityDetailModel *detailModel = x;
        SEGActivityType actType = [detailModel.actType integerValue];
        SEGActivityDetailBaseViewController *vc;
        switch (actType) {//活动类型(1:征集类,2:抽奖类,3:投票类,4:调查类,5:线下类,6:签到类,7:触发类)
            case SEGActivityType_Collect: /*征集类*/
            {
                vc = [[SEGActivityCollectViewController alloc] init];
                break;
            }
            case SEGActivityType_Lottery: /*抽奖类*/
            {
                vc = [[SEGActivityLotteryViewController alloc] init];
                break;
            }
            case SEGActivityType_OffLine: /*线下类*/
            {
                vc = [[SEGActivityOffLineViewController alloc] init];
                break;
            }
            case SEGActivityType_Sign: /*签到类*/
            {
                SEGActivitySignViewController *vc = [[SEGActivitySignViewController alloc] init];
                vc.actId = actId;
                vc.hidesBottomBarWhenPushed = YES;
                [nav pushViewController:vc animated:YES];
                return;
            }
            case SEGActivityType_Trigger: /*触发类*/
            {
                vc = [[SEGActivityTriggerViewController alloc] init];
                break;
            }
        }
        vc.actId = actId;
        vc.hidesBottomBarWhenPushed = YES;
        [nav pushViewController:vc animated:YES];
    } error:^(NSError * _Nullable error) {
        [SVProgressHUD dismiss];
        if (error.code == -3) {//活动被删除 显示删除界面
            SEGActivityDetailBaseViewController *vc = [[SEGActivityDetailBaseViewController alloc] init];
            vc.actId = actId;
            vc.hidesBottomBarWhenPushed = YES;
            [nav pushViewController:vc animated:YES];
            return;
        }
        [SEGAlertView showTmepMessageWithMessage:error.localizedDescription];
    }];
}

/**
 * 初始化中奖记录列表
 * @author Wendy
 * @param params  跳转参数
 */
- (UIViewController*)segAction_initWinRecordListViewController:(NSDictionary*)params
{
    SEGWinRecordListViewController *VC = [[SEGWinRecordListViewController alloc]init];
    return VC;
}

/**
 * 初始化中奖记录详情
 * @author Wendy
 * @param params  跳转参数，必传参数winnerId
 */
- (UIViewController*)segAction_initWinRecordDetailViewController:(NSDictionary*)params
{
    SEGWinRecordDetailViewController *VC= [[SEGWinRecordDetailViewController alloc] initWithWinnerId:ValueToString([params valueForKey:@"winnerId"])];
    return VC;
}

/**
 * 初始化活动邀请函界面
 * @author Wendy
 * @param params  跳转参数
 */
- (UIViewController*)segAction_initActivityInvitationViewController:(NSDictionary*)params
{
    SEGActivityInvitationViewController *VC = [[SEGActivityInvitationViewController alloc]initWithActId:ValueToString([params valueForKey:@"actId"])];
    
    return VC;
}

/**
 * 初始化活动出发抽奖界面
 * @author Wendy
 * @param params  跳转参数
 */
- (UIViewController*)segAction_initActivityTriggerLotteryViewController:(NSDictionary*)params
{
    // 获取本地抽奖信息 (不是用参数 直接取本地数据)
    NSArray *array = [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"%@_%@",kActivityLotteryInfoArrayNew, kAccountUserID]];
    if(!array || array.count == 0) {//新路径获取不到，获取老数据
        array = [[NSUserDefaults standardUserDefaults] objectForKey:kActivityLotteryInfoArray];
    }
    if (array.count > 0) {
        NSDictionary *info = array[0];
        NSDictionary *params = @{
            @"actId" : info[@"actId"] ?: @"",
            @"lotteryId" : info[@"lotteryId"] ?: @"",
            @"triggerEventId" : info[@"triggerEventId"] ?: @""
        };
        // 初始化抽奖界面
        SEGActivityTriggerLotteryViewController *vc = [[SEGActivityTriggerLotteryViewController alloc] init];
        vc.actId = ValueToString([params valueForKey:@"actId"]);
        vc.lotteryId = ValueToString([params valueForKey:@"lotteryId"]);
        vc.triggerEventId = ValueToString([params valueForKey:@"triggerEventId"]);
        return vc;
    }
    return nil;
}

/**
 * 初始化活动签到界面
 * @author Wendy
 * @param params  跳转参数
 */
- (UIViewController*)segAction_initActivitySignViewController:(NSDictionary*)params
{
    SEGActivitySignViewController *vc = [[SEGActivitySignViewController alloc] init];
    vc.actId = ValueToString([params valueForKey:@"actId"]);
    return vc;
}

/**
 * 活动请求
 * @author Sam
 * @param params  跳转参数
 */
- (void)segAction_requestSubmitEventWithEventName:(NSDictionary*)params
{
    NSString *eventName = [[params allKeys]containsObject:@"EventName"]? [params valueForKey:@"EventName"]:@"";
    NSString *eventValue = [[params allKeys]containsObject:@"eventValue"]? [params valueForKey:@"eventValue"]:@"";

    [[self.viewModel.submitEventCommand execute:RACTuplePack(eventName, eventValue)] subscribeNext:^(id  _Nullable x) {
    } completed:^{
        
    }];
}

/**
 * 检查是否显示活动抽奖气泡
 * @author Wendy
 * @param params  跳转参数，必传参数 vc:当前视图控制器
 */
- (void)segAction_checkActivityLotteryBubble:(NSDictionary*)params {
    // 若配置了不展示抽奖气泡，则不请求数据
    if ([SEGCommonConfig shared].isHideLotteryBtn) return;
    
    UIViewController *vc = [params objectForKey:@"vc"];
    if (!vc) {
        return;
    }
    
    BOOL shouldShow = YES;
    // 当前页面是Tab主页面才展示抽奖气泡
    if (!vc.navigationController || vc.navigationController.viewControllers.firstObject != vc) {
        shouldShow = NO;
    }
    
    //活动列表界面结构不同，currentViewController最后一个是SEGActivityRootViewController
    Class activityDetailVC = NSClassFromString(@"SEGActivityDetailBaseViewController");
    Class activityRootVC = NSClassFromString(@"SEGActivityRootViewController");
    Class activitySignVC = NSClassFromString(@"SEGActivitySignViewController");
    if ([vc isKindOfClass:activityRootVC] || [vc isKindOfClass:activityDetailVC] || [vc isKindOfClass:activitySignVC]) {
        shouldShow = YES;
    }
    if(shouldShow) {
        CGFloat bottomPadding = 20;
        //活动列表和详情的底部间距和其他界面不一样
        Class actList = NSClassFromString(@"SEGActivityListViewController");
        Class actDetail = NSClassFromString(@"SEGActivityDetailBaseViewController");
        Class actSign = NSClassFromString(@"SEGActivitySignViewController");
        if ([vc isKindOfClass:actList] || [vc isKindOfClass:actDetail] || [vc isKindOfClass:actSign]) {
            bottomPadding = 64+LYSafeAreaBottom();
        }
        
        // 第一次展示抽奖气泡需要初始化
        if (!vc.lotteryButton) {
            SEGActivityLotteryBubbleButton *lotteryButton = [[SEGActivityLotteryBubbleButton alloc] init];
            lotteryButton.hidden = YES;
            [vc.view addSubview:lotteryButton];
            vc.lotteryButton = lotteryButton;
        }
        [vc.lotteryButton updateShowStatusWithBottomPadding:bottomPadding];
    }
}

- (UIViewController *)seg_currentViewController {
    UIViewController *resultVC;
    resultVC = [self seg_topViewController:[[UIApplication sharedApplication].keyWindow rootViewController]];
    while (resultVC.presentedViewController) {
        resultVC = [self seg_topViewController:resultVC.presentedViewController];
    }
    return resultVC;
}

- (UIViewController *)seg_topViewController:(UIViewController *)vc {
    if ([vc isKindOfClass:[UINavigationController class]]) {
        return [self seg_topViewController:[(UINavigationController *)vc topViewController]];
    } else if ([vc isKindOfClass:[UITabBarController class]]) {
        return [self seg_topViewController:[(UITabBarController *)vc selectedViewController]];
    } else {
        return vc;
    }
    return nil;
}

/// 获取签到气泡按钮
- (UIButton *)segAction_getSignButton:(NSDictionary*)params {
    SEGActivitySignBubbleButton *signButton = [[SEGActivitySignBubbleButton alloc] init];
    signButton.hidden = YES;
    return (UIButton *)signButton;
}

/**
 * 检查是否显示活动签到气泡
 * @author Wendy
 * @param params  跳转参数，必传参数 nav:当前控制器导航栏, view:当前视图
 */
- (void)segAction_checkActivitySignBubble:(NSDictionary*)params {
    SEGActicityCheckSignButtonShowBlock checkBlock = [params objectForKey:@"checkBlock"];
    UIView *signBubble = [params objectForKey:@"signButton"];
    if ([signBubble isKindOfClass:[SEGActivitySignBubbleButton class]]) {
        SEGActivitySignBubbleButton *tempSignBubble = (SEGActivitySignBubbleButton *)signBubble;
        tempSignBubble.hidden = YES;
        tempSignBubble.pressblock = nil;
    }
    
    /*
    签到、任务气泡逻辑
    1. 纷享页 服务页先请求签到接口
    2. 签到接口完成，如果不展示签到，判断本地是否关闭过任务悬浮窗，如未关闭则请求任务列表
    3. 任务列表成功并且未完成的任务，则展示任务悬浮窗
    */
    [self.viewModel.checkSignShowSignal subscribeNext:^(id  _Nullable x) {
        RACTupleUnpack(NSString *homeSignActId, NSNumber *isShow) = x;
        
        // 给签到气泡添加设置事件
        SEGActivitySignBubbleButton *tempSignBubble = nil;
        if ([signBubble isKindOfClass:[SEGActivitySignBubbleButton class]]) {
            tempSignBubble = (SEGActivitySignBubbleButton *)signBubble;
            __weak __block SEGActivitySignBubbleButton *tempSignBubble = (SEGActivitySignBubbleButton *)signBubble;
            tempSignBubble.pressblock = ^{
                SEGActivitySignViewController *signVC = [[SEGActivitySignViewController alloc] init];
                signVC.actId = ValueToString(homeSignActId);
                signVC.hidesBottomBarWhenPushed = YES;
                [tempSignBubble.viewController.navigationController pushViewController:signVC animated:YES];
            };
        }
        
        // 展示签到气泡
        if (isShow.boolValue) {
            [tempSignBubble displaySignBubble];
            if (checkBlock) {
                checkBlock(homeSignActId, YES);
            }
            return;
        }
        
        // [bugfix 34636]先将signID返回再请求任务列表,防止任务列表失败或者用户点击主页右上角的时候没有带signID
        if (checkBlock) {
            checkBlock(homeSignActId, NO);
        }
        
    } error:^(NSError * _Nullable error) {
    }];
}

/**
 * 隐藏活动抽奖气泡
 * @author Wendy
 * @param params  跳转参数
 */
- (void)segAction_hiddenActivityLotteryBubble:(NSDictionary*)params
{
    [SEGActivityLotteryBubbleButton hiddenLotteryBubble];
}

/**
 * 隐藏活动签到气泡
 * @author Wendy
 * @param params  跳转参数
 */
- (void)segAction_hiddenActivitySignBubble:(NSDictionary*)params
{
    [SEGActivitySignBubbleButton hiddenSignBubble];
}

/**
 v1.0.0
 消息回复列表要判断类型，活动的评论跳转活动评论详情

 @param params @{@"parentObjId": @""}
 @return activityCommentVC
 */
- (UIViewController *)segAction_initActivityCommonDetailViewController:(NSDictionary *)params {
    SEGActivityCommentDetailViewController *activityCommentVC = [[SEGActivityCommentDetailViewController alloc] initWithQuizId:ValueToString(params[@"parentObjId"]) actId:@"" actName:@""];
    return activityCommentVC;
}

/// 展示完成活动任务详情列表弹窗
/// @param params 跳转传参
- (void)segAction_showFinishActivityTaskDetailViewController:(NSDictionary *)params {
    // 未登录 不处理
    if ([SEGLoginV2Manager seg_getSignOutStatus]) return;
    
    SEGFinishActivityTaskDetailViewController *vc = [[SEGFinishActivityTaskDetailViewController alloc] init];
    // 传参
    if (params[@"exampleId"]) vc.exampleId = params[@"exampleId"];
    if (params[@"completeTaskTitle"]) vc.completeTaskTitle = params[@"completeTaskTitle"];
    if (params[@"completeTaskDesc"]) vc.completeTaskDesc = params[@"completeTaskDesc"];
    if (params[@"whetherShowLottery"]) vc.whetherShowLottery = params[@"whetherShowLottery"];
    if (params[@"lotteryId"]) vc.lotteryId = params[@"lotteryId"];
    if (params[@"actId"]) vc.actId = params[@"actId"];
    if (params[@"triggerEventId"]) vc.triggerEventId = params[@"triggerEventId"];
    if (params[@"lotteryType"]) vc.lotteryType = params[@"lotteryType"];
    
    // 从获取当前窗口顶层视图
    UIViewController *topVC = [[SEGUhomeMediator sharedInstance] seg_getCurrentController:nil];
    if (topVC.navigationController) {
        [self showFinishActivityTaskDetailViewController:vc currentNavigationController:topVC.navigationController];
        return;
    } else {
        // 从获取栈顶视图
        UIViewController *stackTopVC = [UIApplication sharedApplication].delegate.window.rootViewController;
        if ([stackTopVC isKindOfClass:[UITabBarController class]]) {
            stackTopVC = ((UITabBarController *)stackTopVC).selectedViewController;
        }
        if ([stackTopVC isKindOfClass:[UINavigationController class]]) {
            if ([stackTopVC.presentedViewController isKindOfClass:[SEGFinishActivityTaskDetailViewController class]]) {
                [(SEGFinishActivityTaskDetailViewController *)topVC seg_refresh];
                return;
            }
            [stackTopVC dismissViewControllerAnimated:NO completion:^{
                [self showFinishActivityTaskDetailViewController:vc currentNavigationController:(UINavigationController *)stackTopVC];
            }];
        }
    }
}
/// 展示完成活动任务详情列表弹窗
/// @param vc 完成活动任务弹窗
/// @param currentNav 基于跳转的导航
- (void)showFinishActivityTaskDetailViewController:(SEGFinishActivityTaskDetailViewController *)vc currentNavigationController:(UINavigationController *)currentNav {
    // present
    SEGStaffDetailPresentationController *presentVC = [[SEGStaffDetailPresentationController alloc] initWithPresentedViewController:vc presentingViewController:currentNav];
    vc.transitioningDelegate = presentVC;
    vc.presentingNav = currentNav;
    [currentNav presentViewController:vc animated:YES completion:nil];
}

/// 任务通过code跳转到对应页面
/// @param childTaskModel 任务详情模型
/// @param nav 导航控制器
/// @param presentVC 活动任务弹窗
/// @return 是否跳转成功
+ (BOOL)getActivityTaskSkipViewController:(SEGActivityChildTaskModel *)childTaskModel presentVC:(UIViewController *)presentVC nav:(UINavigationController *)nav {
    // 跳转动画
    BOOL presentAnimated = YES;
    // 已完成的任务不进行跳转
    if (childTaskModel.whetherComplete == 1) {
        return NO;
    }
    
    NSString *moduleCode = ValueToString(childTaskModel.moduleCode);
    NSString *businessId = ValueToString(childTaskModel.businessId);
    NSString *surveyDetailLink = ValueToString(childTaskModel.surveyDetailLink);
    
    UIViewController *nextController = nil;
    
    // 话题详情(有id跳详情 没id跳聊聊广场)
    if ([moduleCode isEqualToString:SEGIntegralModule.topicDetail]) {
        if (businessId.integerValue > 0) {
            nextController = [[SEGUhomeMediator sharedInstance] seg_initTopicDetailViewController:@{@"objId":businessId}];
        } else {
            nextController = [[SEGUhomeMediator sharedInstance] seg_initTalkSquareViewController:nil];
        }
    }
    
    // 邻里圈
    if ([moduleCode isEqualToString:SEGIntegralModule.neighborhoodCircle]) {
        [presentVC dismissViewControllerAnimated:presentAnimated completion:^{
            [[SEGUhomeMediator sharedInstance] seg_selctedToTabWithAction:@"TAB_UGC"];
        }];
        return YES;
    }
    
    // PGC日报详情(有id跳转详情 没id跳转纷享tab)
    if ([moduleCode isEqualToString:SEGIntegralModule.articleDetail]) {
        if (businessId.integerValue > 0) {
            nextController = [[SEGUhomeMediator sharedInstance] seg_initPGCDeteailViewController:@{@"pictorialId":businessId, @"needCountDown":@(YES)}];
        } else {
            [presentVC dismissViewControllerAnimated:presentAnimated completion:^{
                [[SEGUhomeMediator sharedInstance] seg_selctedToTabWithAction:@"TAB_SHARE"];
            }];
            return YES;
        }
    }
    
    // 邀请邻居
    if ([moduleCode isEqualToString:SEGIntegralModule.inviteNeighbor]) {
        nextController = [[SEGUhomeMediator sharedInstance] seg_initInviteViewController:nil];
    }
    
    // 调查问卷(有id跳转详情 没有跳转问卷调查列表)
    if ([moduleCode isEqualToString:SEGIntegralModule.surveyDetail]) {
        if (surveyDetailLink.length > 0) {
            NSString *link = surveyDetailLink;
            if (businessId.integerValue > 0) {
                link = [link stringByAppendingString:businessId];
            }
            nextController = [[SEGUhomeMediator sharedInstance] seg_initWebViewLoadController:@{@"linkURL":link}];
        }
    }
    
    // 个人主页
    if ([moduleCode isEqualToString:SEGIntegralModule.profilePage]) {
        nextController = [[SEGUhomeMediator sharedInstance] seg_initMyProfileViewController:@{}];
    }
    
    // 纷享 tab
    if ([moduleCode isEqualToString:SEGIntegralModule.enjoy]) {
        [presentVC dismissViewControllerAnimated:presentAnimated completion:^{
            [[SEGUhomeMediator sharedInstance] seg_selctedToTabWithAction:@"TAB_SHARE"];
        }];
        return YES;
    }
    
    // 聊聊广场
    if ([moduleCode isEqualToString:SEGIntegralModule.chatSquare]) {
        nextController = [[SEGUhomeMediator sharedInstance] seg_initTalkSquareViewController:nil];
    }
    
    // 活动广场
    if ([moduleCode isEqualToString:SEGIntegralModule.activitySquare]) {
        nextController = [[SEGTarget_ActivityManage new] segAction_initActivityRootViewController:nil];
    }
    
    // 主站(ID必传 没有ID跳转失败)
    if ([moduleCode isEqualToString:SEGIntegralModule.mainStation]) {
        if (businessId.integerValue > 0) {
            nextController = [[SEGUhomeMediator sharedInstance] seg_initChannelViewController:@{@"channelId":businessId}];
        }
    }
    
    // 活动详情(id选填 没有跳转活动广场)
    if ([moduleCode isEqualToString:SEGIntegralModule.activityDetail]) {
        if (businessId.integerValue > 0) {
            [presentVC dismissViewControllerAnimated:presentAnimated completion:^{
                [[SEGTarget_ActivityManage new] segAction_goToActivityDetailViewController:@{@"actId": businessId, @"nav":nav}];
            }];
            return YES;
        } else {
            nextController = [[SEGTarget_ActivityManage new] segAction_initActivityRootViewController:nil];
        }
    }
    
    if (nextController) {
        [presentVC dismissViewControllerAnimated:presentAnimated completion:^{
            [nav pushViewController:nextController animated:YES];
        }];
        return YES;
    }
    
    // 不能跳转 给与提示
    [SEGAlertView showTmepMessageWithMessage:kMessageForTaskJumpFail];
    return NO;
}

#pragma mark - Getter
- (SEGActivityDetailViewModel *)viewModel {
    if (!_viewModel) {
        _viewModel = [[SEGActivityDetailViewModel alloc] init];
    }
    return _viewModel;
}

- (SEGSignActivityDetailViewModel *)taskViewModel {
    if (!_taskViewModel) {
        _taskViewModel = [[SEGSignActivityDetailViewModel alloc] init];
    }
    return _taskViewModel;
}

@end
